import { View, ActivityIndicator } from 'react-native';
import RootSiblingsManager from 'react-native-root-siblings';
import EventEmitter from 'eventemitter3';
import { primaryColor } from '@/constants/Colors';
import { isIos } from '@/utils/helper';
import styles from './styles';

export const loadingEvent = new EventEmitter();
export const eventType = Symbol('@loading');

let rootNode: RootSiblingsManager | null = null;

const createLoading = (hasLoading = true) => {
  return (
    <View style={[
      styles.loading,
      hasLoading && styles.hasContent
    ]}
    >
      {hasLoading && (
        <View style={styles.content}>
          <ActivityIndicator
            size={isIos() ? 48 : 36}
            color={primaryColor}
          />
        </View>
      )}
    </View>
  );
}

export const showLoading = (hasLoading = true) => {
  if (rootNode) return;
  const loading = createLoading(hasLoading);
  loadingEvent.emit(eventType, true);
  rootNode = new RootSiblingsManager(loading);
}

export const closeLoading = () => {
  rootNode?.destroy();
  rootNode = null;
  loadingEvent.emit(eventType, false);
}

export const globalLoading = {
  open: showLoading,
  close: closeLoading
}

export default globalLoading;